package com.jiang.专题.区间.Q56;

import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;

/**
 * @author Jiang
 * @version 1.0
 * @date 2025/04/27 17:00
 */
public class Solution {
    public int[][] merge(int[][] intervals) {
        PriorityQueue<int[]> queue = new PriorityQueue<>((o1, o2) -> {
            if (o1[0] != o2[0]) {
                return o1[0] - o2[0];
            } else {
                return o1[1] - o2[1];
            }
        });
        for (int[] interval : intervals) {
            queue.offer(interval);
        }
        List<int[]> list = new ArrayList<>();
        int[] interval = queue.poll();
        int i = interval[0], j = interval[1], index = 0;
        while (!queue.isEmpty()) {
            interval = queue.poll();
            if (interval[0] <= j) {
                j = Math.max(interval[1], j);
            } else {
                list.add(new int[]{i, j});
                i = interval[0];
                j = interval[1];
            }
        }
        list.add(new int[]{i, j});
        return list.toArray(int[][]::new);
    }
}
